<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<script type="text/javascript">
require([
    "prototype"
], function(){

    var DateOption = Class.create({

        getDaysInMonth: function(month, year)
        {
            var curDate = new Date();
            if (!month) {
                month = curDate.getMonth();
            }
            if (2 == month && !year) { // leap year assumption for unknown year
                return 29;
            }
            if (!year) {
                year = curDate.getFullYear();
            }
            return 32 - new Date(year, month - 1, 32).getDate();
        },

        reloadMonth: function(event)
        {
            var selectEl = event.findElement();
            var idParts = selectEl.id.split("_");
            if (idParts.length != 3) {
                return false;
            }
            var optionIdPrefix = idParts[0] + "_" + idParts[1];
            var month = parseInt($(optionIdPrefix + "_month").value);
            var year = parseInt($(optionIdPrefix + "_year").value);
            var dayEl = $(optionIdPrefix + "_day");

            var days = this.getDaysInMonth(month, year);

            //remove days
            for (var i = dayEl.options.length - 1; i >= 0; i--) {
                if (dayEl.options[i].value > days) {
                    dayEl.remove(dayEl.options[i].index);
                }
            }

            // add days
            var lastDay = parseInt(dayEl.options[dayEl.options.length-1].value);
            for (i = lastDay + 1; i <= days; i++) {
                this.addOption(dayEl, i, i);
            }
        },

        addOption: function(select, text, value)
        {
            var option = document.createElement('OPTION');
            option.value = value;
            option.text = text;

            if (select.options.add) {
                select.options.add(option);
            } else {
                select.appendChild(option);
            }
        }
    });

    window.dateOption = new DateOption();

});
</script>
